/*
 * 文件名：RSAUtils.java
 * 版权：Copyright by http://www.infopub.top/
 * 描述：
 * 修改人：Awoke
 * 修改时间：2019年1月8日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.util.security;


import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
* <p>
* RSA加签|验签| 加密|解密 工具
* </p>
* <p>
* dataBytes需调用方.getBytes("<B>UTF-8</B>")编码<br/>
* </p>
* 
* @author Awoke
* @version 2019年1月8日
* @see RsaUtil
* @since
*/
@Component
public class RsaUtil {

    /**
     * 加密算法RSA
     */
    private static final String KEY_ALGORITHM = "RSA";

    /**
    * 签名算法
    */
    private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";

    /**
     * 加密填充方式
     */
    private static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";

    // 密钥长度为1024时，RSA加密明文最大长度117字节，解密要求密文最大长度为128字节，所以在加密和解密的过程中需要分块进行。
    // RSA加密对明文的长度是有限制的，如果加密数据过大会抛出如下异常：
    // Exception in thread "main" javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes  

    /**
     * RSA最大加密明文大小 字节数
     */
    private static final int MAX_ENCRYPT_BLOCK = (RsaKeyBuilder.DEFAULT_KEY_SIZE / 8) - 11;

    /**
     * RSA最大解密密文大小 字节数
     */
    private static final int MAX_DECRYPT_BLOCK = (RsaKeyBuilder.DEFAULT_KEY_SIZE / 8);

    /**
     * 私钥(BASE64编码)
     */
    @Value("${rsa.private.key.base64:not-configured}")
    private String privateKey;

    /**
     * 公钥(BASE64编码)
     */
    @Value("${rsa.public.key.base64:not-configured}")
    private String publicKey;

    /**
    * <p>
    * [私钥]对信息生成数字签名
    * </p>
    * @param data 已加密数据
    * @return
    * @throws Exception
    */
    public String sign(byte[] data)
        throws Exception {
        // 私钥必须是PKCS8
        byte[] keyBytes = Base64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateK);
        signature.update(data);
        return Base64.encodeBase64String(signature.sign());
    }

    /**
    * <p>
    * [公钥]校验数字签名
    * </p>
    * @param data 已加密数据
    * @param sign 数字签名
    * @return
    * @throws Exception
    */
    public boolean verify(byte[] data, String sign)
        throws Exception {
        byte[] keyBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicK = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicK);
        signature.update(data);
        return signature.verify(Base64.decodeBase64(sign));
    }

    /**
    * <P>
    * [私钥]解密
    * </p>
    * @param encryptedData 已加密数据
    * @return
    * @throws Exception
    */
    public byte[] decryptByPrivateKey(byte[] encryptedData)
        throws Exception {
        byte[] keyBytes = Base64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, privateK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            }
            else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++ ;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    /**
    * <p>
    * [公钥]解密
    * </p>
    * @param encryptedData 已加密数据
    * @return
    * @throws Exception
    */
    public byte[] decryptByPublicKey(byte[] encryptedData)
        throws Exception {
        byte[] keyBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, publicK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            }
            else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++ ;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    /**
    * <p>
    * [公钥]加密
    * </p>
    * @param data 源数据
    * @return
    * @throws Exception
    */
    public byte[] encryptByPublicKey(byte[] data)
        throws Exception {
        byte[] keyBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            }
            else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++ ;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
    * <p>
    * [私钥]加密
    * </p>
    * @param data 源数据
    * @return
    * @throws Exception
    */
    public byte[] encryptByPrivateKey(byte[] data)
        throws Exception {
        byte[] keyBytes = Base64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, privateK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            }
            else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++ ;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

}